package com.jinjiafeng.baselibrary.permission;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jinjiafeng
 * Data：18-5-24-下午2:11
 * Description:
 */
class PermissionUtils {

    private PermissionUtils(){}
    public static boolean isOverMarshmallow(){
        return Build.VERSION.SDK_INT>Build.VERSION_CODES.M;
    }

    static void executeSucceedMethod(Object obj, int requestCode) {
        final Method[] methods = obj.getClass().getDeclaredMethods();
        for (Method method : methods) {
            final PermissionSuccess success = method.getAnnotation(PermissionSuccess.class);
            if(success!=null){
                final int value = success.requestCode();
                if(requestCode == value){
                    executeMethod(obj, method);
                }
            }
        }
    }

    static void executeFailedMethod(Object obj, int requestCode) {
        final Method[] methods = obj.getClass().getDeclaredMethods();
        for (Method method : methods) {
            final PermissionFailed failed = method.getAnnotation(PermissionFailed.class);
            if(failed!=null){
                final int value = failed.requestCode();
                if(requestCode == value){
                    executeMethod(obj, method);
                }
            }
        }
    }

    private static void executeMethod(Object obj, Method method) {
        try {
            method.setAccessible(true);
            method.invoke(obj);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    static List<String> getDeniedPermission(Object obj, String[] permissions) {
        final ArrayList<String> deniedList = new ArrayList<>();

        for (String permission : permissions) {
            final int result = ContextCompat.checkSelfPermission(getActivity(obj), permission);
            if(result!=PackageManager.PERMISSION_GRANTED){
                deniedList.add(permission);
            }
        }
        return deniedList;

    }

    static Activity getActivity(Object obj) {
        if(obj instanceof Activity){
            return (Activity) obj;
        }
        if(obj instanceof Fragment){
            return ((Fragment) obj).getActivity();
        }
        return null;
    }
}
